package com.lsh.controller;

import com.lsh.domain.User;
import com.lsh.domain.UserDatum;
import com.lsh.exception.SysException;
import com.lsh.service.IndexService;
import com.lsh.service.SetService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/user")
public class SetController {

    @Autowired
    IndexService indexService;
    @Autowired
    SetService setService;

    /**
     * 个人中心
     * @param mv
     * @return
     */
    @RequestMapping(value = "/set")
    public ModelAndView setting(@CookieValue("TOKEN") String token, ModelAndView mv){
        String userId = indexService.findByUserId(token);
        UserDatum userDatum = setService.findByUserDatum(Integer.parseInt(userId));
        User user = setService.findByUser(Integer.parseInt(userId));
        mv.addObject("nickname", userDatum.getNickname());
        mv.addObject("pro", userDatum.getProvince());
        mv.addObject("cit", userDatum.getCity());
        mv.addObject("email", user.getEmail());
        mv.addObject("mobile", user.getMobile());
        mv.setViewName("user/setting");
        return mv;
    }

    /**
     * 修改用户密码
     * @param token
     * @param oldPwd
     * @param newPwd
     * @param mv
     * @return
     * @throws SysException
     */
    @RequestMapping(value = "/updatePwd", method = RequestMethod.POST)
    public ModelAndView updatePassword(@CookieValue("TOKEN") String token, @RequestParam("oldPwd") String oldPwd,
                                       @RequestParam("newPwd") String newPwd, ModelAndView mv) throws SysException {
        String userId = indexService.findByUserId(token);
        String message = setService.updatePassword(userId, newPwd, oldPwd);
        mv.addObject("SUCCESS", message);
        JSONObject jo = new JSONObject();
        jo.putAll(mv.getModel());
        mv.clear();
        mv.addObject("data", jo.toString());
        mv.setViewName("/JSON");
        return mv;
    }


}
